<template>
	<view style="	background: rgba(247, 247, 247, 1);">
		<proSwiperVue :barHeight="barHeight" :backShow="true" :swiperImg="titleInfo?.carousel_images"
			:swiperHeight="swiperH" :Firstvideo="video">
		</proSwiperVue>
		<view>
			<!-- 标题介绍 -->
			<titleIntroductionVue :titleInfo="titleInfo" :favoriteState="favoriteState"></titleIntroductionVue>
		</view>
		<view>
			<!-- 权益 -->
			<benefitsCardVue :titleInfo="right_interest"></benefitsCardVue>
		</view>
		<view>
			<!-- 套餐卡片 -->
			<packageCardVue :type_number="typeNumber" :packageCardInfo="packageCardInfo" @click="clickCard">
			</packageCardVue>
		</view>
		<!-- 点击出发更多类型 -->
		<view class="click-more">
			快速了解不同类型的主要区别
			<text @click="moreShow">点击查看</text>
		</view>
		<!-- 横向滑动日期卡片 -->
		<view>
			<dateListVue @DatePickShow="datePickShow" :dateListInfo="dateListInfo" :dayId="shop_cost_id"
				@clickDate="clickDate"></dateListVue>
		</view>
		<!-- 日历卡片弹窗 -->
		<view>
			<datePickPopVue ref="isDatePickPop" @selectOne="selectDate" @nextSele="DateNext"
				:packageCardInfo="packageCardInfo" @clickType="clickType" :ticketInfo="dateListInfo"
				:dayId="shop_cost_id" :type_number="typeNumber" :active_days="active_days"></datePickPopVue>
		</view>

		<view>
			<!-- 出行卡片 -->
			<vehicleTypeVue :vehicleTypeInfo="vehicleTypeInfo"></vehicleTypeVue>
		</view>
		<view>
			<!-- 住宿类型 -->
			<accommodationTypeVue :accommodationTypeInfo="accommodationTypeInfo"></accommodationTypeVue>
		</view>
		<view>
			<!--推荐领队	 -->
			<recommendedLeaderVue :data="leaderInfo" @lookLeader="LookLeader"></recommendedLeaderVue>
		</view>

		<view>
			<!-- 锚点栏 -->
			<view class="tab-buttons" v-show="isAnchorBarVisible" :style="{height:navbarHeight +'px'}">
				<view class="tab-button-box"
					:style="{height:capsuleHeight +'px', top:TimeBarHeight + 'px',lineHeight: capsuleHeight + 'px'}">
					<view class="tab-button" :class="{ active: activeAnchor === 'itinerary' }"
						@click="scrollToSection('itinerary')">行程内容</view>
					<view class="tab-button" :class="{ active: activeAnchor === 'details' }"
						@click="scrollToSection('details')">详情内容</view>

					<view class="tab-button" :class="{ active: activeAnchor === 'finePrint' }"
						@click="scrollToSection('finePrint')">预购须知</view>
				</view>
			</view>
			<!-- 其他组件保持不变... -->
			<view>
				<!-- 行程内容 -->
				<itineraryVue id="itinerary" :tripDetailsInfo="tripDetailsInfo"></itineraryVue>
				<!-- 详情内容 -->
				<view id="details" class="rich-text">
					<text>详情内容</text>
					<rich-text style="padding-top: 10rpx;" :nodes="richdata"></rich-text>
				</view>

				<!-- 预购须知内容 -->
				<finePrintVue id="finePrint" :inclusions="inclusions"></finePrintVue>
			</view>
		</view>
		<view class="reserve-box">
			<view class="text-box">
				<view class="text">
					<!-- 6月17日出发-6月19日返程 -->
				</view>
				<view class="button" @click="toOrder()">
					预定
				</view>
			</view>
		</view>
	</view>

	<moreTypesPopVue ref="isMoreTypesPopS"></moreTypesPopVue>
	<leaderPopVue ref="isLeaderPops" :PersonInfo="leaderPersonInfo"></leaderPopVue>
	<peopleChoosePopVue ref="isPeopleChoosePop" :Currentcount="currentCount" @result="nextStep" />
	<!-- <BackTopVue></BackTopVue> -->
</template>

<script setup>
	import {
		ref,
		onUnmounted,
		nextTick,
		watch,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onPageScroll,
		onShow
	} from '@dcloudio/uni-app'
	import proSwiperVue from './components/proSwiper.vue';
	import titleIntroductionVue from './components/titleIntroduction.vue';
	import benefitsCardVue from './components/benefitsCard.vue';
	import packageCardVue from './components/packageCard.vue';
	import moreTypesPopVue from './components/moreTypesPop.vue';
	import dateListVue from './components/dateList.vue';
	import datePickPopVue from './components/datePickPop.vue';
	import vehicleTypeVue from './components/vehicleType.vue';
	import accommodationTypeVue from './components/accommodationType.vue';
	import recommendedLeaderVue from './components/recommendedLeader.vue';
	import leaderPopVue from './components/leaderPop.vue';
	import itineraryVue from './components/itinerary.vue';
	import finePrintVue from './components/finePrint.vue';
	import peopleChoosePopVue from './components/peopleChoosePop.vue';
	import BackTopVue from '../../components/BackTop.vue';
	import {
		navbarHeight,
		capsuleHeight,
		TimeBarHeight
	} from '@/config/systemInfo';
	import {
		GetTripshop,
		GetTripDateTicket
	} from '@/config/API/ProductDetails';

	const shopID = ref()
	const favoriteState = ref()
	//获取票价的请求
	const getDateTicket = async (tripshopid) => {
		const res = await GetTripDateTicket(tripshopid)
		if (res.code == 200) {
			return res.data
		}
		if (res.code !== 200) {
			return uni.showToast({
				title: '网络错误',
				icon: 'none'
			})
		}
	}
	onLoad((option) => {
		shopID.value = option.ShopId
		console.log('接收的商品iD', shopID.value);
	})
	onShow(async () => {
		if (typeof window !== 'undefined') {
			window.addEventListener('scroll', handleScroll);
		}
		nextTick(async () => {
			//获得旅游商品信息
			const userid = uni.getStorageSync('userInfo').id
			const GetTripshopRes = await GetTripshop(shopID.value, userid)
			if (GetTripshopRes && GetTripshopRes.code === 200) {
				// 这里确保了GetTripshopRes对象存在且其code属性值为200
				TripshopInfo.value = GetTripshopRes;
				console.log('TripshopInfo.value', TripshopInfo.value);
				titleInfo.value = TripshopInfo.value.data.trip_data[0];
				favoriteState.value = TripshopInfo.value.data.trip_status
				active_days.value = titleInfo.value.active_days
				video.value = titleInfo.value.viedo
				console.log('video.value', video.value);
				// TODO富文本
				// richdata.value = titleInfo.value.detail_show
				richdata.value = titleInfo.value.detail_show
				//费用包含
				inclusions.value = titleInfo.value.inclusions
				console.log('inclusions.value', JSON.parse(inclusions.value));
				// 商品id
				shop_id.value = titleInfo.value.shop_id
				console.log('shop_id.value ', shop_id.value);
				//权益
				// let right_interested = titleInfo.value.right_interest.replace(/^\[|\]|\,$/g, '').trim();
				// let formattedString = right_interested.replace(/'/g, '').split(',');
				right_interest.value = titleInfo.value.right_interest
				console.log('right_interest', right_interest.value);
				//
				packageCardInfo.value = TripshopInfo.value.data.trip_types;
				console.log('packageCardInfo', packageCardInfo.value);
				//给初始number赋值
				typeNumber.value = packageCardInfo.value[0].type_number
				console.log('typeNumber', typeNumber.value);
				vehicleTypeInfo.value = TripshopInfo.value.data.trip_vehicle;
				accommodationTypeInfo.value = TripshopInfo.value.data.trip_hotel;
				tripDetailsInfo.value = TripshopInfo.value.data.trip_details;
				leaderInfo.value = TripshopInfo.value.data.trip_leader;
			} else {
				console.log('后端没了');
			}
			// 获得日期的对应票数量和价格
			// 异步数据获取
			const AlldateList = await getDateTicket(shopID.value);
			if (AlldateList) {
				AlldateListInfo.value = AlldateList;
				console.log('AlldateListInfo', AlldateListInfo.value);
				const res = AlldateList.filter(item => item.type_number == typeNumber.value);
				if (res.length > 0) {
					dateListInfo.value = res[0].dates; // 确保 `dateListInfo` 是响应式的

					console.log('传递给子组件前的 dateListInfo:', dateListInfo.value);
				} else {
					console.log('未找到匹配的日期数据');
				}
			}
		})

		// 获取状态栏的高度
		const barTop = uni.getSystemInfoSync().statusBarHeight;
		// 获取胶囊按钮的位置信息
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		const computedBarHeight = barTop + menuButtonInfo.top;
		// barHeight.value = `${computedBarHeight}rpx`;
		barHeight.value = computedBarHeight;
		// 动态获取导航栏高度
		if (typeof document !== 'undefined') {
			window.addEventListener('scroll', handleScroll);
		}
	});
	//旅游商品详情的所有内容
	const TripshopInfo = ref()
	const video = ref('')
	const active_days = ref()
	// 商品id
	const shop_id = ref()
	const currentCount = ref(8)
	//标题介绍卡片
	const titleInfo = ref()
	//权益
	const right_interest = ref([])
	// 套餐卡片信息
	const packageCardInfo = ref()
	const typeNumber = ref()
	///出行卡片
	const vehicleTypeInfo = ref()
	//酒店参考卡片
	const accommodationTypeInfo = ref()
	// 所有不同规格的票价及个数
	const AlldateListInfo = ref()
	//选中不同规格的票价及个数
	const dateListInfo = ref()
	//起始时间-回队时间
	const startToEnd = ref()
	//选中票
	const shop_cost_id = ref()
	const shop_data_id = ref()
	//每日行程卡片
	const tripDetailsInfo = ref()
	//领队卡片
	const leaderInfo = ref()
	const richdata = ref("111")
	//轮播图高度
	const swiperH = ref(440)
	const barHeight = ref(0)
	//展示更多套餐类型的弹窗
	const isMoreTypesPopS = ref(null)
	//选择时间弹窗
	const isDatePickPop = ref(null)
	//人数选择弹窗
	const isPeopleChoosePop = ref(null)
	// 滚动锚点
	const isAnchorBarVisible = ref(true);
	const activeAnchor = ref(''); // 新增变量来追踪当前活动的锚点
	// 费用包含
	const inclusions = ref([])
	let scrollTimeout = null; // 用于防抖
	watch(() => typeNumber.value, (newValue) => {
		console.log('newNumber===>', newValue);
		if (newValue) {
			shop_cost_id.value = ''
		}
	});
	// 当前滚动位置
	let currentScrollY = 0;

	const scrollToSection = async (sectionId) => {
		console.log('barHeight.value', barHeight.value);
		await nextTick(); // 确保DOM更新完成
		if (typeof document !== 'undefined') {
			const section = document.getElementById(sectionId);
			if (section) {
				const headerOffset = barHeight.value || 0;
				const sectionPosition = section.getBoundingClientRect().top + window.scrollY - headerOffset;
				// 暂停滚动事件中的activeAnchor更新
				pauseActiveAnchorUpdate();

				window.scrollTo({
					top: sectionPosition,
					behavior: 'smooth'
				});
				// activeAnchor.value = sectionId; // 更新当前活动的锚点
				// 滚动完成后更新activeAnchor
				setTimeout(() => {
					activeAnchor.value = sectionId;
					resumeActiveAnchorUpdate();
				}, 200); // 根据需要调整时间，以匹配滚动动画的时间
			}
		} else {
			uni.createSelectorQuery().select(`#${sectionId}`).boundingClientRect((rect) => {
				if (rect) {
					const targetScrollTop = rect.top + currentScrollY - (barHeight.value || 0);
					uni.pageScrollTo({
						scrollTop: targetScrollTop,
						duration: 300
					});
					// 滚动完成后更新activeAnchor
					setTimeout(() => {
						activeAnchor.value = sectionId;
					}, 300); // 根据需要调整时间，以匹配滚动动画的时间
				}
			}).exec();
		}
		activeAnchor.value = sectionId; // 更新当前活动的锚点
	};
	// 暂停滚动事件中的activeAnchor更新
	const pauseActiveAnchorUpdate = () => {
		scrollTimeout = setTimeout(() => {}, 0);
	};

	// 恢复滚动事件中的activeAnchor更新
	const resumeActiveAnchorUpdate = () => {
		clearTimeout(scrollTimeout);
	};
	// 处理滚动事件
	let lastScrollY = 0;

	const sections = ['itinerary', 'details', 'finePrint']; // 添加要监控的部分ID

	const handleScroll = (event) => {
		console.log('barHeight.value', barHeight.value);
		currentScrollY = event?.scrollTop || window.scrollY || 0;
		isAnchorBarVisible.value = currentScrollY < lastScrollY; // 向上滚动时显示锚点栏
		lastScrollY = currentScrollY;
		// 使用防抖来限制滚动事件触发频率
		if (scrollTimeout) {
			clearTimeout(scrollTimeout);
		}
		scrollTimeout = setTimeout(() => {
			// 更新 activeAnchor
			let newActiveAnchor = '';
			let closestDistance = Infinity;

			const query = uni.createSelectorQuery(); // 创建选择器查询

			sections.forEach((sectionId) => {
				query.select(`#${sectionId}`).boundingClientRect((rect) => {
					if (rect) {
						const sectionTop = rect.top + currentScrollY; // 计算每个部分距离页面顶部的距离
						const distance = Math.abs(sectionTop - currentScrollY); // 计算距离

						if (distance < closestDistance) {
							closestDistance = distance;
							newActiveAnchor = sectionId; // 更新最近的活动锚点
						}
					}
				});
			});

			// 执行选择器查询
			query.exec(() => {
				activeAnchor.value = newActiveAnchor; // 更新当前活动的锚点
			});
		}, 100); // 根据需要调整时间，以平衡性能和响应速度

	};

	onMounted(() => {
		// 动态获取导航栏高度
		// if (typeof document !== 'undefined') {
		// 	const navbar = document.querySelector('.tab-buttons');
		// 	if (navbar) {
		// 		barHeight.value = navbar.offsetHeight;
		// 	}
		// }
	})
	onPageScroll(handleScroll);



	onUnmounted(() => {
		if (typeof window !== 'undefined') {
			window.removeEventListener('scroll', handleScroll);
		}
	});

	//套餐卡片选择
	const clickCard = (e) => {
		console.log('套餐卡片选择===>', e);
		typeNumber.value = e.type_number;
		console.log('typeNumber.value===>', typeNumber.value);
		const res = AlldateListInfo.value.filter(item => item.type_number == typeNumber.value);
		if (res.length === 0) {
			uni.showToast({
				title: '所选套餐暂无对应的可选择日期',
				icon: 'none'
			});
			return;
		}
		dateListInfo.value = res[0].dates;
		console.log('便利出来的==>', dateListInfo.value);
	};
	// 汽车卡片选择
	const clickVehicle = (e) => {}
	// 点击查看 查看类型
	const moreShow = () => {
		console.log('dadadadadadadadadada');
		isMoreTypesPopS.value.showPopup()
	}
	//点击弹出全部日期
	const datePickShow = () => {
		isDatePickPop.value.showPopup(typeNumber.value)
	}
	const clickType = (item, typenumber) => {
		console.log('clickType', item, typenumber);
		typeNumber.value = item.type_number;
		console.log('typeNumber.value===>', typeNumber.value);
		const res = AlldateListInfo.value.filter(item => item.type_number == typeNumber.value);
		if (res.length === 0) {
			uni.showToast({
				title: '所选套餐暂无对应的可选择日期',
				icon: 'none'
			});
			return;
		}
		dateListInfo.value = res[0].dates;
		console.log('便利出来的==>', dateListInfo.value);
	}
	//选择出行日期
	const selectDate = (selectedDateInfo) => {
		shop_cost_id.value = selectedDateInfo.shop_cost_id
		currentCount.value = selectedDateInfo.count
		shop_data_id.value = selectedDateInfo.shop_data_id
		console.log('selectedDateInfo', selectedDateInfo);
	}
	// 横向卡片选择日期
	const clickDate = (id) => {
		isDatePickPop.value.showPopup(typeNumber.value)
		// uni.showToast({
		// 	title: '请打开全部日期选择或点击预定',
		// 	icon: 'none'
		// })
		// day_id.value = id
	}
	//点击下一步
	const DateNext = (startDate, endDate, selectedDate) => {
		console.log('开始日期:', startDate);
		console.log('结束日期:', endDate);
		console.log('选择的日期:', selectedDate);
		startToEnd.value = `${startDate}-${endDate}`
		console.log('startToEnd.value', startToEnd.value);
		console.log('shop_cost_id', shop_cost_id.value);
		if (shop_cost_id.value) {
			isPeopleChoosePop.value.showPopup()
		} else {
			uni.showToast({
				title: '请选择日期',
				icon: 'none'
			})
		}
	}
	// 领队弹窗
	// 领队弹窗信息
	const leaderPersonInfo = ref()
	const isLeaderPops = ref(null)
	const LookLeader = (id) => {
		console.log('index我点到的领队', id);
		isLeaderPops.value.showPopup()
		const person = leaderInfo.value.find(item => item.leader_id == id)
		leaderPersonInfo.value = person
	}
	//点击 预定后 弹出人数选择窗
	const toOrder = () => {
		isDatePickPop.value.showPopup(typeNumber.value)
	}
	const nextStep = (e) => {
		console.log('人数：', e);
		if (typeNumber.value && shop_cost_id.value) {
			if (packageCardInfo.value) {
				const res = AlldateListInfo.value.filter(item => item.type_number == typeNumber.value)
				console.log('res==>', res);
				let order_detail = res[0].type_name
				const dayidres = res[0].dates.filter(item => item.shop_cost_id == shop_cost_id.value)
				console.log('dayidres.cost_final', dayidres[0]);
				const cost_final = dayidres[0].cost_final
				console.log('cost_final', cost_final);
				console.log('packageCardInfo', packageCardInfo.value);
				const typeInfo = packageCardInfo.value.find(item => item.type_number === typeNumber.value)
				const type_price_difference = Number(typeInfo.type_price_difference)
				console.log('type_price_difference', type_price_difference);
				uni.navigateTo({
					url: `/homeSubpages/orderConfirm/orderConfirm?peoples=${e}&typeNumber=${typeNumber.value}&shop_cost_id=${shop_cost_id.value}&shop_id=${shop_id.value}&cost_final=${cost_final}&startToEnd=${startToEnd.value}&type_price_difference=${type_price_difference}&order_detail=${order_detail}&shop_data_id=${shop_data_id.value}&active_days=${titleInfo.value.active_days}&coverImage=${titleInfo.value.carousel_images[0]}&right_interest=${JSON.stringify(right_interest.value)}`
				})
				isPeopleChoosePop.value.closePopup()
			}

		} else {
			uni.showToast({
				title: '请选择日期和人数',
				icon: 'none'
			})
		}

	}
</script>

<style scoped>
	.click-more {
		width: 100%;
		font-size: 24rpx;
		font-weight: 400;
		color: rgba(125, 125, 125, 1);
		margin: 10rpx auto;
		text-align: center;
	}

	.click-more text {
		font-size: 24rpx;
		font-weight: 400;
		color: rgba(95, 152, 217, 1);
	}

	.reserve-box {
		position: sticky;
		bottom: 0;
		background-color: rgba(255, 255, 255, 1);
		border-radius: 18rpx;
		padding: 24rpx 24rpx 54rpx 24rpx;
		box-sizing: border-box;
		display: flex;
		gap: 30rpx;
		flex-direction: column;
		margin-bottom: 30rpx;
		z-index: 9;
	}

	.text-box {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.text-box .text {
		width: 100%;
		text-align: center;
		font-size: 20rpx;
		font-weight: 400;
		color: rgba(166, 166, 166, 1);
	}

	.text-box .button {
		width: 100%;
		text-align: center;
		opacity: 1;
		color: rgba(255, 255, 255, 1);
		border-radius: 56rpx;
		background: rgba(54, 48, 48, 1);
		box-shadow: 0rpx 4rpx 8rpx rgba(0, 0, 0, 0.25);
		padding: 20rpx 0;
		box-sizing: border-box;
	}

	.tab-buttons {
		position: sticky;
		top: 0rpx;
		display: flex;
		gap: 10px;
		margin-bottom: 10px;
		padding: 0 20rpx;
		box-sizing: border-box;

		background: rgba(247, 247, 247, 1);
	}

	.tab-button {
		font-size: 28rpx;
		font-weight: 400;
		color: rgba(203, 203, 203, 1);
		padding: 0 30rpx;
		transition: background-color 0.3s, color 0.3s;
	}

	.tab-button-box {
		position: absolute;
		display: flex;
	}

	.tab-button.active {
		font-size: 30rpx;
		font-weight: 400;
		color: rgba(56, 56, 56, 1);
		border-bottom: 10rpx solid rgba(56, 56, 56, 1);
	}

	.rich-text {
		border-radius: 20rpx;
		width: calc(100% - 40rpx);
		margin: 0 auto;
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		letter-spacing: 2rpx;
	}


	.rich-text text {
		font-size: 32rpx;
		font-weight: 600;
		color: rgba(21, 11, 71, 1);
	}
</style>